var tree = layui.tree
    ,layer = layui.layer
    ,table = layui.table
    ,$ = layui.jquery,form=layui.form,
    tableid=getQueryVariable("tableid"),
    modelId=getQueryVariable("modelId"),
    partsParentTempId=getQueryVariable("partsParentTempId");
var data = [{
    title: ''
    ,id: 1
    ,field: ''
    ,children: []
},{
    title: '一级2'
    ,id: 2
    ,field: ''
    ,children: [{
        title: '二级2-1'
        ,id: 5
        ,field: ''
        ,children: [{
            title: '三级2-1-1'
            ,id: 11
            ,field: ''
        },{
            title: '三级2-1-2'
            ,id: 12
            ,field: ''
        }]
    },{
        title: '二级2-2'
        ,id: 6
        ,field: ''
        ,children: [{
            title: '三级2-2-1'
            ,id: 13
            ,field: ''
        },{
            title: '三级2-2-2'
            ,id: 14
            ,field: ''
            ,disabled: true
        }]
    }]
},{
    title: '一级3'
    ,id: 16
    ,field: ''
    ,children: [{
        title: '二级3-1'
        ,id: 17
        ,field: ''
        ,fixed: true
        ,children: [{
            title: '三级3-1-1'
            ,id: 18
            ,field: ''
        },{
            title: '三级3-1-2'
            ,id: 19
            ,field: ''
        }]
    },{
        title: '二级3-2'
        ,id: 27
        ,field: ''
        ,children: [{
            title: '三级3-2-1'
            ,id: 28
            ,field: ''
        },{
            title: '三级3-2-2'
            ,id: 29
            ,field: ''
        }]
    }]
}];
var data0 = [{
    id: "1",
    contracttype: "text1",
    productimg: "statics/images/layui-logo.jpg",
    number: "3",
    batchno: "333",
    delivery: "333",
    salesunitprice: "333",
    costsubtotal: "333",
    amountsubtotal: "333",
    deliverycost: "333",
    apportionment: "333",
    currency: "333",
}, {
    id: "2",
    contracttype: "text1",
    productimg: "statics/images/layui-logo.jpg",
    number: "3",
    batchno: "333",
    delivery: "333",
    salesunitprice: "333",
    costsubtotal: "333",
    amountsubtotal: "333",
    deliverycost: "333",
    apportionment: "333",
    currency: "333",
}, {id: "3", contracttype: "text1", productimg: "statics/images/layui-logo.jpg", number: "3", batchno: "333",
    delivery: "333",
    salesunitprice: "333",
    costsubtotal: "333",
    amountsubtotal: "333",
    deliverycost: "333",
    apportionment: "333",
    currency: "333",}];
var cataCode="1";
var selectdata=[];//产品目录
var cataCode="",cataCodeName="";
var cataCodeList="";//产品目录code
query();
queryPid();
getCatalogBycode("1");
/*//ajax得到目录 给select赋值
$("#directory").html("");

$("#directory").append("<option value=''></option>");
//var directory = [{name: 1, value: "text1"}, {name: 2, value: "text2"}, {name: 3, value: "text3"}];
for (var i = 0; i < selectdata.length; i++) {
    cataCode=selectdata[0].id;
    cataCodeName=selectdata[0].name;
    $("#directory").append("<option value=\"" + selectdata[i].id + "\">" + selectdata[i].name + "</option>");
}*/



/*form.val("editor-form",{
    "cataCode":cataCode
});
form.render();*/
//form.render('select');
//---公司目录
tree.render({
    elem: '#statisticslist' //默认是点击节点可进行收缩
    ,data: data
    ,id:"producttreeid",
    tree: {
        iconIndex: 1,           // 折叠图标显示在第几列
        isPidData: false,        // 是否是id、pid形式数据
        idName: 'fileid',  // id字段名称
    },
    page: false
    ,onlyIconControl: true  //是否仅允许节点左侧图标控制展开收缩
    ,click: function(obj){

        cataCode=obj.data.code;
        form.val("editor-form",{
            "cataCode":cataCode
        });
        form.render();
        //判断是否有选中的列，有则取消换现点击列
        var selecteds = $(".selecteds");
        if(typeof (selecteds[0])!="undefined"){
            selecteds.removeClass("selecteds");
        }
        obj.elem[0].classList.add("selecteds");
        getCatalogBycode(obj.data.code);
        //obj.data为点击菜单的数据
        table.reload('companydirectorytableid', {
           // data:data0 ,
            method: 'post'
            ,url:"productmaininfo/selectBjByPage"
            ,page: {
                curr: 1 //重新从第 1 页开始
            }
            ,where:{
                "cataCode":cataCodeList,//此处替换为
                // "cataCode": obj.data.code,
                "code":"",
                "chinaName":"",
                "englishName":"",
                "gecode":"",
                "ge":""
            }
        }, 'data');
    }
});
table.render({
    elem: '#companydirectory'
    //,data:data0
    ,method: 'post'
    ,url:"productmaininfo/selectBjByPage"
    ,where:{
        "cataCode":cataCodeList,
       // "cataCode": obj.data.code,
        "deactivateType":1

    }
    ,toolbar: '#toolbarDemo'
    ,cols: [[
        /*{checkbox: true, fixed: true}
        ,{field: 'productimg', title: '图片', width: 120, align: 'center', templet: '#imgTpl'}
        ,{field:'productcode', width: 120, title:'产品编码', sort: true}
        ,{field:'specificationcoding', width: 120, title:'规格编码', sort: true}
        ,{field:'specification', width: 120, title:'规格说明', sort: true}
        ,{field:'chinesename', width: 120, title:'中文名称', sort: true}
        ,{field:'englishnam', width: 120, title:'英文名称', sort: true}
        ,{field: 'chinesedescription', width: 120, title: '中文描述', sort: true}
        ,{field: 'englishdescription', width: 120, title: '英文描述', sort: true}
        ,{field : 'grossweight',width: 120,title : '毛重',sort : true}
        ,{field : 'netweight',width: 120,title : '净重',sort : true}
        ,{field:'outerpackingsize', title:'外包装尺寸', sort: true}*/
        {type:"checkbox", fixed: true}
        ,{field: 'img', title: '图片', width: 120, align: 'center', templet: '#imgTpl'},
        {field: 'code', width: 120, title: '产品编码', sort: true,event:'productcode'},
        {field: 'chinaName', width: 120, title: '中文名称', sort: true},
        {field: 'englishName', width: 120, title: '英文名称', sort: true},

        {field: 'hgCode', width: 120, title: '海关编码', sort: true},

        {field:'taxRate', title:'退税率',  width: 120,sort: true},
        {field:'importTariff', title:'关税税率', width: 120, sort: true},

        {field: 'gecode', width: 120, title: '规格编码', sort: true},
        {field: 'ge', width: 120, title: '规格说明', sort: true},
        {field: 'bzsm', width: 120, title: '包装说明', sort: true},
        {field: 'cpjz', width: 120, title: '产品净重', sort: true},
        {field: 'cpmz', width: 120, title: '产品毛重', sort: true}
    ]]
    ,id: 'companydirectorytableid'
    ,height: 530
    ,page: true
    , done: function (res, curr, count) {
        $(".layui-table select").parent(".layui-table-cell").css('overflow','visible')
        $(".layui-form-select").parents(".layui-table-cell").css('overflow','visible')
        hoverOpenImg();//显示大图

        setselecttype(selectdata,'directory');

    }
});
setselecttype(selectdata,'directory');
form.render();
form.on('submit(submitform)', function(data){
    layer.msg(JSON.stringify(data.field));
    data.field.deactivateType=1;
    table.reload('companydirectorytableid', {
        page: {
            curr: 1 //重新从第 1 页开始
        }
        ,where: data.field
    }, 'data');
    return false;
});
//右侧搜索
form.on("submit(form-search)",function (data) {
    cataCode=$("#directory option:selected")[0].value;
    getCatalogBycode(cataCode);
    table.reload('companydirectorytableid', {
        // data:data0 ,
        method: 'post'
        ,url:"productmaininfo/selectBjByPage"
        ,page: {
            curr: 1 //重新从第 1 页开始
        }
        ,where:{
            "cataCode":cataCodeList,//$("#directory option:selected")[0].value,//此处替换为
            // "cataCode": obj.data.code,
            "code":$("input[name='code']")[0].value,
            "chinaName":$("input[name='chinaName']")[0].value,
            "englishName":$("input[name='englishName']")[0].value,
            "gecode":$("input[name='gecode']")[0].value,
            "ge":$("input[name='ge']")[0].value
        }
    }, 'data');
    setselecttype(selectdata,'directory');
    form.val("editor-form",{
        "cataCode":cataCode
    });
    form.render();
});

let customsCode = [];
$("#choose").on("click",function () {
    let companydirectory =   table.checkStatus("companydirectorytableid").data;
    if(companydirectory.length == 0){
        layer.msg("请选择数据")
    }else{
        //保存成功关闭此页面
        let oldData =  parent.table.cache[tableid];
        if(tableid == "storageproductstableid" && modelId == "offer"){
            //报价相关
            //交货日期
            let deliveryDate = parent.$("#carryTime").val();
            if(isEmpty(deliveryDate)){
                deliveryDate = currentDate;
            }
            $.each(companydirectory, function (index, value) {
                let tempId = GenNonDuplicateID(3) + (index+1);
                //产品信息
                companydirectory[index]["id"] = null;
                //临时id
                companydirectory[index]["tempId"] = tempId;
                //交货日期
                companydirectory[index]["deliveryDate"] = deliveryDate;
                //产品编码
                companydirectory[index]["productCode"] = companydirectory[index].code;
                //规格编码
                companydirectory[index]["specificationCode"] = companydirectory[index].gecode;
                //规格说明
                companydirectory[index]["specificationExplanation"] = companydirectory[index].ge;
                //客户货号
                companydirectory[index]["clientProductNo"] = companydirectory[index].customerCode;
                //中文名称
                companydirectory[index]["productCname"] = companydirectory[index].chinaName;
                //英文名称
                companydirectory[index]["productEname"] = companydirectory[index].englishName;
                //中文描述
                companydirectory[index]["productCdesc"] = companydirectory[index].chinaRemark;
                //英文描述
                companydirectory[index]["productEdesc"] = companydirectory[index].englishRemark;
                //单位名称
                companydirectory[index]["productUnitName"] = companydirectory[index].dw;
                //单价
                companydirectory[index]["unitPrice"] = companydirectory[index].fob;
                //颜色
                companydirectory[index]["color"] = companydirectory[index].colour;
                //人民币采购价（采购成本）
                companydirectory[index]["purchasePriceRmb"] = companydirectory[index].cgcb;
                //美金采购价（默认为零）
                companydirectory[index]["purchasePriceUsd"] = 0;
                //金额小计（默认为零）
                companydirectory[index]["moneySubtotal"] = 0;
                //利润额（默认为零）
                companydirectory[index]["profitMargin"] = 0;
                //利润率（默认为零）
                companydirectory[index]["profitMarginRatio"] = 0;
                //仓库费用金额（默认为零）
                companydirectory[index]["warehouseCostAmount"] = 0;
                //40HQ海运费（默认为零）
                companydirectory[index]["fortyOceanFreight"] = 0;
                //数量（默认为零）
                companydirectory[index]["productNum"] = 0;
                //金额小计（默认为零）
                companydirectory[index]["moneySubtotal"] = 0;
                //边际利润率（默认为零）
                companydirectory[index]["marginalProfitRatio"] = 0;

                //40HQ
                companydirectory[index]["fortyHq"] = companydirectory[index].hq40zl;
                //供应商名称
                companydirectory[index]["supplierName"] = companydirectory[index].gys;
                //海关编码
                companydirectory[index]["customsCode"] = companydirectory[index].hgCode;
                if(!isEmpty(companydirectory[index].hgCode)){
                    for(let i in customsCode){
                        if(customsCode[i].code == companydirectory[index].hgCode){
                            //报关品名
                            companydirectory[index]["nameCustomsDeclaration"] = customsCode[i].name;
                            //英文品名
                            companydirectory[index]["englishProductName"] = customsCode[i].englishName;
                            //报关单位
                            companydirectory[index]["customsDeclarationUnit"] = customsCode[i].unitOfQuantity;
                            //进口关税
                            companydirectory[index]["importTariffs"] = customsCode[i].importTariff;
                            //退税率
                            companydirectory[index]["taxRebateRate"] = customsCode[i].taxRate;
                            //增值税率
                            companydirectory[index]["vatRate"] = customsCode[i].vatRate;
                            break;
                        }
                    }
                }

                //配件信息
                //产品编码
                let productCode = companydirectory[index].code;
                //获取规格编码
                let specNo = companydirectory[index].gecode;
                let partsList = [];
                $.ajax({
                    url: "offer/getProductPartsInfoBySpecNo?specNo=" + specNo + "&productCode=" + productCode,
                    async:false,
                    success:function(data){
                        if(data.status == 200){
                            for(let i in data.data){
                                let partTempId = GenNonDuplicateID(3) + (index+1);
                                data.data[i]["tempId"] = partTempId;
                                data.data[i]["parentTempId"] = tempId;
                                partsList.push(data.data[i]);
                            }
                        }else {
                            layer.msg("获取信息失败，请稍后再试！", {icon: 5});
                        }
                    }
                });
                companydirectory[index]["partsList"] = partsList;

                oldData.push(companydirectory[index]);
            });


        } else if(tableid == "productsatableid" && modelId == "offer"){
            //配件导入
            let parentTableDate =  parent.table.cache["storageproductstableid"];
            for(let i in parentTableDate){
                if(parentTableDate[i].tempId == partsParentTempId){
                    //产品数量
                    let productNum = parentTableDate[i].productNum;
                    if(isEmpty(productNum)){
                        productNum = 0;
                    }
                    let purchaseNo = "";
                    if(!isEmpty(parentTableDate[i]["purchaseNo"])){
                        purchaseNo = parentTableDate[i]["purchaseNo"];
                    }
                    $.each(companydirectory, function (index, value) {
                        let tempId = GenNonDuplicateID(3) + (index+1);
                        companydirectory[index]["id"] = null;
                        //临时id
                        companydirectory[index]["tempId"] = tempId;
                        //对应产品临时id
                        companydirectory[index]["parentTempId"] = partsParentTempId;
                        //配件编码 = 产品编码
                        companydirectory[index]["partsCode"] = companydirectory[index].code;
                        //规格编码
                        companydirectory[index]["specNo"] = companydirectory[index].gecode;
                        //成品比例(默认1)
                        companydirectory[index]["proportionFinishedProducts"] = 1;
                        //配件比例(默认1)
                        companydirectory[index]["partsFinishedProducts"] = 1;
                        //数量:配件数量 = 对应产品数量*配件比例
                        companydirectory[index]["partsAmount"] = productNum;
                        //中文名称
                        companydirectory[index]["productCname"] = companydirectory[index].chinaName;
                        //英文名称
                        companydirectory[index]["productEname"] = companydirectory[index].englishName;
                        //采购单号
                        companydirectory[index]["purchaseNo"] = purchaseNo;
                        //毛重
                        companydirectory[index]["grossWeight"] = companydirectory[index].cpmz;
                        //净重
                        companydirectory[index]["netWeight"] = companydirectory[index].cpjz;
                        //体积(没有体积,默认为空)
                        companydirectory[index]["bulk"] = "";

                        parentTableDate[i].partsList.push(companydirectory[index]);
                    });

                    parent.table.reload("storageproductstableid",{data : parentTableDate, limit : parentTableDate.length});
                    oldData = parentTableDate[i].partsList;
                    break;
                }
            }

        }else {
            $.each(companydirectory, function (index, value) {
                oldData.push(companydirectory[index]);
            });
        }

        parent.table.reload(tableid,{data : oldData, limit : oldData.length});

        //执行接口
        layer.msg("保存成功", {icon: 6});
        setTimeout(function () {
            //保存成功则关闭此页面
            var index = parent.layer.getFrameIndex(window.name);
            parent.layer.close(index);
        },1000)
    }
});
$("#shutdown").on("click",function () {
    var index = parent.layer.getFrameIndex(window.name);
    parent.layer.close(index);
});
//产品库导入搜索
/*table.on('toolbar(companydirectorytable)', function(obj){
    alert("asdfa");
});
$("#search").on("click",function () {
    $("input[name='code']")[0].value;//产品编码
    $("input[name='chinaName']")[0].value;//中文名称
    $("input[name='gecode']")[0].value;//规格编码
    $("input[name='englishName']")[0].value;//英文名称
    $("input[name='ge']")[0].value;//规格说明
    $("#directory option:selected")[0].value;//目录
    table.reload('companydirectorytableid', {
        // data:data0 ,
        type:"get"
        ,url:"productmaininfo/selectBjByPage"
        ,page: {
            curr: 1 //重新从第 1 页开始
        }
        ,where:{
            "cataCode":$("#directory option:selected")[0].value,//此处替换为
            // "cataCode": obj.data.code,
            "code":$("input[name='code']")[0].value,
            "chinaName":$("input[name='chinaName']")[0].value,
            "englishName":$("input[name='englishName']")[0].value,
            "gecode":$("input[name='gecode']")[0].value,
            "ge":$("input[name='ge']")[0].value$("input[name='ge']")[0].value
        }
    }, 'data');

});*/
//---自建目录
tree.render({
    elem: '#statisticslists' //默认是点击节点可进行收缩
    ,data: data
    ,onlyIconControl: true  //是否仅允许节点左侧图标控制展开收缩
    ,click: function(obj){
        //判断是否有选中的列，有则取消换现点击列
        var selectedss = $(".selectedss");
        if(typeof (selectedss[0])!="undefined"){
            selectedss.removeClass("selectedss");
        }
        obj.elem[0].classList.add("selecteds");
        //obj.data为点击菜单的数据
        table.reload('statisticstableid', {
            data:data0 ,
            page: {
                curr: 1 //重新从第 1 页开始
            }
            ,where: obj.data.id
        }, 'data');
    }
});
table.render({
    elem: '#selfbuiltdirectory'
    ,data:data0
    ,toolbar: '#toolbarDemos'
    ,cols: [[
        {checkbox: true, fixed: true}
        ,{field: 'productimg', title: '图片', width: 120, align: 'center', templet: '#imgTpl'}
        ,{field:'productcode', width: 120, title:'产品编码', sort: true}
        ,{field:'specificationcoding', width: 120, title:'规格编码', sort: true}
        ,{field:'specification', width: 120, title:'规格说明', sort: true}
        ,{field:'chinesename', width: 120, title:'中文名称', sort: true}
        ,{field:'englishnam', width: 120, title:'英文名称', sort: true}
        ,{field: 'chinesedescription', width: 120, title: '中文描述', sort: true}
        ,{field: 'englishdescription', width: 120, title: '英文描述', sort: true}
        ,{field : 'grossweight',width: 120,title : '毛重',sort : true}
        ,{field : 'netweight',width: 120,title : '净重',sort : true}
        ,{field:'outerpackingsize', title:'外包装尺寸', sort: true}
    ]]
    ,id: 'selfbuiltdirectorytableid'
    ,height: 530
    ,page: true
    , done: function (res, curr, count) {
        $(".layui-table select").parent(".layui-table-cell").css('overflow','visible')
        hoverOpenImg();//显示大图
    }
});
form.on('submit(submitforms)', function(data){
    layer.msg(JSON.stringify(data.field));
    table.reload('selfbuiltdirectorytableid', {
        data:data0 ,
        page: {
            curr: 1 //重新从第 1 页开始
        }
        ,where: data.field
    }, 'data');
    return false;
});

$("#chooses").on("click",function () {
    var selfbuiltdirectory =   table.checkStatus("selfbuiltdirectorytableid").data;
    if(selfbuiltdirectory.length == 0){
        layer.msg("请选择数据");
    }else{
        //执行接口
        var oldData =  parent.table.cache["storageproductstableid"];
        $.each(selfbuiltdirectory, function (index, value) {
            oldData.push(selfbuiltdirectory[index]);
        });
        parent.table.reload('storageproductstableid',{data : oldData}); //刷新银行信息表格
        layer.msg("保存成功", {icon: 6});
        setTimeout(function () {
            //保存成功则关闭此页面
            var index = parent.layer.getFrameIndex(window.name);
            parent.layer.close(index);
        },1000);
    }
});

$("#shutdowns").on("click",function () {
    var index = parent.layer.getFrameIndex(window.name);
    parent.layer.close(index);
});

function hoverOpenImg() {
    var img_show = null; // tips提示
    $("body").delegate("td img", "mouseover", function () {
        var img = "<img class='img_msg' src='" + $(this).attr('src') + "' style='width:130px;' />";
        img_show = layer.tips(img, this, {
            tips: [2, 'rgba(41,41,41,.5)']
            , area: ['160px']
        });
    });
    $("body").delegate("td img", "mouseout", function () {
        layer.close(img_show);
    });
}

function query(){
    $.ajax({
        type : 'get',
        //  url : 'resource/getTree',
        // data:{"ids":JSON.stringify(distributionid),"saleman":data.field.customersalesman},
        url:'productcatalog/select',
        dataType:"json",
        /*  contentType: 'application/json',*/
        async:false,
        success : function (da) {
            if(da.status==200 ){
                data=getdatas(da.data.children);

            }
        },
        error: function(data) {
            // layer.msg("获取失败!");
        }
    });
}
function getdatas(da){
    var objs=[];
    for(var i=0;i<da.length;i++){
        if(da[i].code=="3"||da[i].code=="4"){
            continue;
        }
        var obj={};
        obj.fileid=da[i].id;
        obj.name=da[i].name;
        obj.type="";
        obj.parentId=da[i].pid;
        obj.path=da[i].path;
        obj.remark=da[i].remark;
        obj.code=da[i].code
        obj.title=obj.name;
        obj.id=obj.fileid;
        if(da[i].children.length !=0 ){
            obj.children=getdatas(da[i].children);
        }

        objs.push(obj);
    }
    return objs;
}
function queryPid() {
    $.ajax({
        type : 'get',
        //  url : 'resource/getTree',
        // data:{"ids":JSON.stringify(distributionid),"saleman":data.field.customersalesman},
        url:'productcatalog/queryPid',
        dataType:"json",
        /*  contentType: 'application/json',*/
        async:false,
        success : function (da) {
            if(da.status==200 ){
                selectdata=da.data;

            }
        },
        error: function(data) {
            // layer.msg("获取失败!");
        }
    });
}

function setselecttype(dt,key) {
    $("#"+key+"").html("");
    var options="";
    for(var i=0;i<dt.length;i++){
        options+="<option value='"+dt[i].code+"'>"+dt[i].name+"</option>";
    }
    $("#"+key+"").append(options);

}
/**
 * 根据产品目录 code获取其下所有的code
 */
function getCatalogBycode(code){
    $.ajax({
        type : 'get',
        //  url : 'resource/getTree',
        // data:{"ids":JSON.stringify(distributionid),"saleman":data.field.customersalesman},
        data:{"code":code},
        url:'productmaininfo/getCatalogBycode',
        dataType:"json",
        /*  contentType: 'application/json',*/
        async:false,
        success : function (da) {
            if(da.status==200 ){
                // selectdata=da.data;
                cataCodeList=JSON.stringify(da.data);
            }
        },
        error: function(data) {
            // layer.msg("获取失败!");
        }
    });
}

//生成临时id
function GenNonDuplicateID(randomLength){
    return Number(Math.random().toString().substr(3,randomLength) + Date.now()).toString(36)
}

//字段是否为空或者零
function isEmpty(obj){
    if(typeof obj == "undefined" || obj == null || obj == "" || obj == 0){
        return true;
    }else{
        return false;
    }
}

layer.ready(function () {
    //获取海关编码信息
    $.ajax({
        url:"offer/getCustomsCode",
        success:function(data){
            if(data.status == 200){
                customsCode = data.data;
            }
        }
    });
});

//时间处理 获取当前时间type:1 yyyy-MM-dd type:2 yyyyMMdd+毫秒
function getNowFormatDate(type) {
    let date = new Date();
    let separator = "-";
    let year = date.getFullYear();
    let month = date.getMonth() + 1;
    let strDate = date.getDate();
    if (month >= 1 && month <= 9) {
        month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
    }
    if(1 == type){
        let currentDate = year + separator + month + separator + strDate;
        return currentDate;
    }else if(2 == type){
        let second = date.getMilliseconds().toString();
        if(second.length < 3){
            if(second.length == 1){
                second = "0" + "0" + second;
            }else {
                second = "0" + second;
            }
        }
        let currentDate = year.toString() + month.toString() + strDate.toString() + second;
        return currentDate;
    }

}

let currentDate = getNowFormatDate(1);